package com.whatech.mall.user.handler;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义Sentinel错误处理。
 */
@Component
public class CustomSentinelUrlBlockHandler implements UrlBlockHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {
        String errorMsg;
        if (ex instanceof FlowException) {
            errorMsg = "限流了";
        } else if (ex instanceof DegradeException) {
            errorMsg = "降级了";
        } else if (ex instanceof ParamFlowException) {
            errorMsg = "热点参数限流了";
        } else if (ex instanceof SystemBlockException) {
            errorMsg = "系统规则限制";
        } else if (ex instanceof AuthorityException) {
            errorMsg = "授权规则限制";
        } else {
            errorMsg = "Sentinel Blocked";
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        objectMapper.writeValue(response.getWriter(), errorMsg);
    }

}
